package com.yhy.common.config;


import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <br>
 * <b>功能：自定义线程池</b><br>
 * <b>作者：</b>yanghuiyuan<br>
 * <b>日期：</b> 2019/12/12 <br>
 * <b>版权所有：<b>版权所有(C) 2019<br>
 */
public class CustomThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public CustomThreadFactory() {
        this("yhy-pool");
    }

    public CustomThreadFactory(String name){
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        //此时namePrefix就是 name + 第几个用这个工厂创建线程池的
        this.namePrefix = name + poolNumber.getAndIncrement();
    }

    @Override
    public Thread newThread(Runnable r) {
        //线程池中第几个执行的线程
        Thread t = new Thread(group, r, namePrefix + "-thread-"+threadNumber.getAndIncrement(),0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}
